<?php

class Admin_RoutesController extends Model3_Scaffold_Controller
{

    public function __construct($request)
    {
        $this->_sc = new Scaffold_DefaultDb_Route();
        parent::__construct($request);
    }

    public function init()
    {
        if (!Model3_Auth::isAuth())
        {
            $this->redirect('Index/index');
        }
    }

    public function indexAction()
    {
        $em = $this->getEntityManager('DefaultDb');
        $pointsRepository = $em->getRepository('DefaultDb_Entities_Point');
        $exchangeCenters = $pointsRepository->getActiveExchangesCenters();
        $routeRepos = $em->getRepository('DefaultDb_Entities_Route');
        $criteria = array(
            'status' => DefaultDb_Entities_Route::STATUS_ACTIVE,
        );
        $typeUser = Model3_Auth::getCredentials('type');
        switch ($typeUser)
        {
            case DefaultDb_Entities_User::USER_OPERATION_CONTROLLER:
                $usersRepository = $em->getRepository('DefaultDb_Entities_User');
                $controllerId = Model3_Auth::getCredentials('id');
                $controller = $usersRepository->findBy(array('id' => $controllerId, 'status' => DefaultDb_Entities_User::STATUS_ACTIVE));
                $criteria['controller'] = $controller;
                break;
        }
        $routes = $routeRepos->findBy($criteria);
        $this->view->getJsManager()->addJsVarEncode('urlDetailRoute', $this->view->url(array(
                    'controller' => 'Routes', 'action' => 'detailRoute')));
        $this->view->whereAmI = array();
        $this->view->hasExchangeCenters = count($exchangeCenters) > 0;
        $this->view->title = 'Rutas';
        $this->view->description = 'Administración de rutas';
        $this->view->routes = $routes;
        $this->view->setTemplate('responsive-3.0');
    }

    public function addAction()
    {
        $msgError = '';
        if ($this->getRequest()->isPost())
        {
            $em = $this->getEntityManager('DefaultDb');
            $routeRepos = $em->getRepository('DefaultDb_Entities_Route');
            $params = $this->getRequest()->getPost();
            if ((empty($params['code']) === false) && (empty($params['name']) === false) && (empty($params['factor']) === false))
            {
                $code = strtoupper(trim($params['code']));
                $name = strtoupper(trim($params['name']));
                $factor = strtoupper(trim($params['factor']));
                if ($routeRepos->existByCode($code) === false)
                {
                    if (is_numeric($factor) === true)
                    {
                        $request = $this->getRequest();
                        // Actualizamos los parametros por su parte en mayusculas y sin espacios
                        $request->setParamPost('code', $code);
                        $request->setParamPost('name', $name);
                        $request->setParamPost('factor', $factor);
                        $request->setParamPost('close', DefaultDb_Entities_Route::OPEN);
                        parent::addAction();
                    }
                    else
                    {
                        $msgError = 'El <strong>factor</strong> debe de ser númerico.';
                    }
                }
                else
                {
                    $msgError = 'Ya existe una ruta con la clave <strong>' . $code . '</strong>.';
                }
            }
            else
            {
                $msgError = 'Todos los campos son obligatorios.';
            }
        }
        $this->view->msgError = $msgError;
        $this->view->whereAmI = array(
            'Rutas' => $this->view->url(array(
                'controller' => 'Routes', 'action' => 'index')));
        $this->view->title = 'Agregar ruta';
        $this->view->description = 'Crear una nueva ruta';
        $this->view->setTemplate('responsive-3.0');
    }

    public function editAction()
    {
        $msgError = '';
        try
        {
            parent::editAction();
        }
        catch (PDOException $exc)
        {
            $code = $exc->getCode();
            switch ($code)
            {
                case 23000: //duplicate key in table
                    $msgError = 'Ya existe una ruta con esta clave.';
                    break;
            }
        }
        $id = $this->getRequest()->getParam('id');
        $this->view->whereAmI = array(
            'Rutas' => $this->view->url(array(
                'controller' => 'Routes', 'action' => 'index')),
            'Editar ruta' => $this->view->url(array(
                'controller' => 'Routes', 'action' => 'edit', 'id' => $id)));
        $this->view->title = 'Editar ruta';
        $this->view->description = 'Modifica los datos de una ruta';
        $this->view->msgError = $msgError;
        $this->view->setTemplate('responsive-3.0');
    }

    public function deleteAction()
    {
        $idRoute = $this->getRequest()->getParam('id');
        $em = $this->getEntityManager('DefaultDb');
        $routesRepository = $em->getRepository('DefaultDb_Entities_Route');
        $route = $routesRepository->find($idRoute);
        $route->setStatus(0);
        $em->persist($route);
        $em->flush();
        $this->view->whereAmI = array(
            'Rutas' => $this->view->url(array(
                'controller' => 'Routes', 'action' => 'index')),
            'Eliminar ruta' => $this->view->url(array(
                'controller' => 'Routes', 'action' => 'delete', 'id' => $idRoute)));
        $this->view->title = 'Eliminar ruta';
        $this->view->description = 'Eliminación de rutas';
        $this->view->setTemplate('responsive-3.0');
    }

    public function pointsAction()
    {
        $routeId = $this->getRequest()->getParam('id');
        $routeSession = new Model3_Session_Namespace('route');
        if (is_null($routeId) == false)
        {
            $routeSession->id = $routeId;
            $em = $this->getEntityManager('DefaultDb');

            $rpRepos = $em->getRepository('DefaultDb_Entities_RoutePoint');
            $routeRepos = $em->getRepository('DefaultDb_Entities_Route');

            $routePoints = $rpRepos->getRoutesPointsByRoute($routeId);
            $route = $routeRepos->find($routeId);
            $this->view->em = $em;
            $this->view->route = $route;
        }
        $this->view->whereAmI = array(
            'Rutas' => $this->view->url(array(
                'controller' => 'Routes', 'action' => 'index')));
        $this->view->getJsManager()->addJsVarEncode('urlToggleCloseRoute', $this->view->url(array(
                    'controller' => 'Routes', 'action' => 'toggleCloseRoute')));
        $this->view->getCssManager()->addCss('view/scripts/Admin/Routes/points.css');
        $this->view->title = 'Puntos de venta';
        $this->view->description = 'Ruta: ' . $route->getName();
        $this->view->setTemplate('responsive-3.0');
    }

    public function detailRouteAction()
    {
        if ($this->getRequest()->isPost() === true)
        {
            $params = $this->getRequest()->getPost();
            if (isset($params['id']) === true)
            {
                $routeId = $params['id'];
                $em = $this->getEntityManager('DefaultDb');
                $routeRepos = $em->getRepository('DefaultDb_Entities_Route');
                $this->view->resumen = $routeRepos->getDetailsRoute($routeId);
            }
        }
        $this->view->setUseTemplate(false);
    }

    /**
     * Esta acción se invoca por ajax y cambia el estatus de la bandera de close
     * de la ruta.
     */
    public function toggleCloseRouteAction()
    {
        $em = $this->getEntityManager('DefaultDb');
        $routeRepository = $em->getRepository('DefaultDb_Entities_Route');
        $routeSession = new Model3_Session_Namespace('route');
        $routeId = $routeSession->id;
        $route = $routeRepository->find($routeId);
        $route->toggleClose();
        $em->persist($route);
        $em->flush();
        $this->view->setUseTemplate(false);
    }

    public function newPointAction()
    {
        if ($this->getRequest()->isPost())
        {
            $msgError = null;
            $params = $this->getRequest()->getPost(true);
            $this->view->errorInsert = $this->addNewPoint($params, $msgError);
            $this->view->msgErrorInsert = $msgError;
        }
        $routeSession = new Model3_Session_Namespace('route');
        $routeId = $routeSession->id;
        if (is_null($routeId) == true)
        {
            $this->redirect('Admin/Routes');
            return;
        }
        else
        {
            $this->view->whereAmI = array(
                'Rutas' => $this->view->url(array('module' => 'Admin', 'controller' => 'Routes',
                    'action' => 'index')),
                'Puntos de venta' => $this->view->url(array('module' => 'Admin',
                    'controller' => 'Routes',
                    'action' => 'points', 'id' => $routeId)));
            $em = $this->getEntityManager('DefaultDb');
            $pointRepository = $em->getRepository('DefaultDb_Entities_Point');
            $rpRepository = $em->getRepository('DefaultDb_Entities_RoutePoint');
            $routeRepos = $em->getRepository('DefaultDb_Entities_Route');
            $stateRepository = $em->getRepository('DefaultDb_Entities_State');
            $route = $routeRepos->findOneById($routeId);
            if ($route->getClose() == DefaultDb_Entities_Route::CLOSE)
            {
                $this->redirect('Admin/Routes/index/');
                return;
            }
            $salePoints = $pointRepository->getActiveSalePoints();
            $exchangeCenters = $pointRepository->getActiveExchangesCenters();
            $pointAdapter = $em->getRepository('DefaultDb_Entities_Point');
            $activeEchangeCenters = $pointAdapter->findBy(array('type' => DefaultDb_Entities_Point::TYPE_EXCHANGE_CENTER,
                'status' => DefaultDb_Entities_Point::STATUS_NORMAL));
            $states = $stateRepository->getAll();
            $points = $rpRepository->getRoutesPointsByRoute($routeId);
            $this->view->em = $em;
            $this->view->isFirstPoint = count($points) == 0;
            $this->view->states = $states;
            $this->view->route = $route;
            $this->view->salePoints = $salePoints;
            $this->view->exchangeCenters = $exchangeCenters;
            $this->view->activeEchangeCenters = $activeEchangeCenters;
            $this->view->scaffoldPoint = new Scaffold_DefaultDb_Point();
            $this->view->getJsManager()->addJs('view/scripts/Admin/Routes/action.js');
            $newRoutePoint = array(
                'module' => 'Admin',
                'controller' => 'Routes',
                'action' => 'ajaxNewRoutePoint'
            );
            $this->view->getJsManager()->addJsVar('newRoutePoint', '"' . $this->view->url($newRoutePoint) . '"');
            $this->view->getJsManager()->addJsVar('urlRechargeInterchangeCenter', '"' . $this->view->url(array(
                        'controller' => 'Routes', 'action' => 'axGetInterchangeExist')) . '"');
            $this->view->getJsManager()->addJsVar('routeId', $routeId);
        }
        $this->view->setTemplate('responsive-3.0');
        $this->view->title = 'Agregar punto de venta';
        $this->view->description = 'Rutas';
    }

    private function addNewPoint($params, &$msgError)
    {
        $em = $this->getEntityManager('DefaultDb');
        $routeRepository = $em->getRepository('DefaultDb_Entities_Route');
        $pointRepository = $em->getRepository('DefaultDb_Entities_Point');
        $routePointRepository = $em->getRepository('DefaultDb_Entities_RoutePoint');
        $statetRepository = $em->getRepository('DefaultDb_Entities_State');
        $success = false;
        $routeSession = new Model3_Session_Namespace('route');
        $routeId = $routeSession->id;
        $route = $routeRepository->find($routeId);
        if (isset($params['typePoint']) === true)
        {
            $typePoint = $params['typePoint'];
            switch ($typePoint)
            {
                case DefaultDb_Entities_Point::TYPE_EXCHANGE_CENTER:
                    if (isset($params['firstPoint']) === true)
                    {
                        $exchangeCenterId = $params['exchangePointId'];
                        $exchangeCenter = $pointRepository->find($exchangeCenterId);
                        $routePointRepository->insertExchangeCenter($route, $exchangeCenter);
                        $success = true;
                    }
                    else
                    {
                        $success = $this->insertExchangeCenter($route, $params, $msgError);
                    }
                    break;
                case DefaultDb_Entities_Point::TYPE_SALE_POINT:
                    if (isset($params['newPoint']) === true)
                    {
                        $success = $this->insertNewSalePoint($route, $params, $msgError);
                    }
                    else
                    {
                        $success = $this->insertSalePoint($route, $params, $msgError);
                    }
                    break;
            }
        }
        return $success;
    }

    /**
     * Insertamos un nuevo punto de venta y lo agregamos a la ruta
     * @param DefaultDb_Entities_Route $route
     * @param type $params
     * @param type $msgError
     * @return boolean true si todo salio bien, false en cualquier otro caso.
     */
    private function insertNewSalePoint(DefaultDb_Entities_Route $route, $params, &$msgError)
    {
        $em = $this->getEntityManager('DefaultDb');
        $pointRepository = $em->getRepository('DefaultDb_Entities_Point');
        $routePointRepository = $em->getRepository('DefaultDb_Entities_RoutePoint');
        $statetRepository = $em->getRepository('DefaultDb_Entities_State');
        $success = false;

        $code = $params['code'];
        $name = $params['name'];
        $address = $params['address'];
        $minutes = $params['minutes'];
        $stateId = $params['state'];
        $required = isset($params['required']);
        if ((empty($code) === false) && (empty($name) === false) && (empty($address) === false) && (empty($minutes) === false))
        {
            if (is_numeric($minutes) === true && $minutes > 0)
            {
                $state = $statetRepository->find($stateId);
                try
                {
                    /// 1) Creamos el NUEVO POINT
                    $newSalePoint = $pointRepository->insertSalePoint($code, $name, $address, $state);
                    /// 2) creamos el NUEVO ROUTE_POINTS
                    $routePointRepository->insertSalePoint($route, $newSalePoint, $minutes, $required);
                    $success = true;
                }
                catch (PDOException $exc)
                {
                    $code = $exc->getCode();
                    switch ($code)
                    {
                        case 23000: //duplicate key in table
                            $msgError = 'Ya existe un punto de venta o centro de intercambio con esta clave.';
                            break;
                        default:
                            $msgError = 'No fue posible crear el punto de venta.';
                            break;
                    }
                }
            }
            else
            {
                $msgError = 'El tiempo debe ser númerico y mayor que 0.';
            }
        }
        else
        {
            $msgError = 'Todos los campos son requeridos.';
        }
        return $success;
    }

    private function insertSalePoint(DefaultDb_Entities_Route $route, $params, &$msgError)
    {
        $em = $this->getEntityManager('DefaultDb');
        $pointRepository = $em->getRepository('DefaultDb_Entities_Point');
        $routePointRepository = $em->getRepository('DefaultDb_Entities_RoutePoint');
        $success = false;

        $salePointId = $params['salePointId'];
        $minutes = $params['minutes'];
        $required = isset($params['required']);
        if (is_numeric($minutes) === true && $minutes > 0)
        {
            $lastPointIdInRoute = $routePointRepository->getLastPointIdByRoute($route->getId());
            if ($lastPointIdInRoute !== null)
            {
                /// Checamos que el punto a agregar a la ruta no sea el mismo al ultimo
                /// punto agregado.
                if ($lastPointIdInRoute != $salePointId)
                {
                    $salePoint = $pointRepository->find($salePointId);
                    $routePointRepository->insertSalePoint($route, $salePoint, $minutes, $required);
                    $success = true;
                }
                else
                {
                    $msgError = 'No es posible asignar un mismo punto 2 veces seguidas a una ruta.';
                }
            }
            else
            {
                $msgError = 'El primer punto de la ruta debe de ser un centro de intercambio vigente.';
            }
        }
        else
        {
            $msgError = 'El tiempo debe ser númerico y mayor que 0.';
        }
        return $success;
    }

    private function insertExchangeCenter(DefaultDb_Entities_Route $route, $params, &$msgError)
    {
        $em = $this->getEntityManager('DefaultDb');
        $pointRepository = $em->getRepository('DefaultDb_Entities_Point');
        $routePointRepository = $em->getRepository('DefaultDb_Entities_RoutePoint');
        $success = false;

        $exchangeCenterId = $params['exchangeCenterId'];
        $minutes = $params['minutes'];
        $required = isset($params['required']);
        $close = isset($params['close']);
        if (is_numeric($minutes) === true && $minutes > 0)
        {
            $lastPointIdInRoute = $routePointRepository->getLastPointIdByRoute($route->getId());
            if ($lastPointIdInRoute !== null)
            {
                /// Checamos que el punto a agregar a la ruta no sea el mismo al ultimo
                /// punto agregado.
                if ($lastPointIdInRoute != $exchangeCenterId)
                {
                    $salePoint = $pointRepository->find($exchangeCenterId);
                    $routePointRepository->insertSalePoint($route, $salePoint, $minutes, $required);
                    /// Cerramos la ruta ya que fue el ultimo punto
                    if ($close === true)
                    {
                        $route->setClose(true);
                        $em->persist($route);
                        $em->flush();
                    }
                    $success = true;
                }
                else
                {
                    $msgError = 'No es posible asignar un mismo punto 2 veces seguidas a una ruta.';
                }
            }
            else
            {
                $msgError = 'El primer punto de la ruta debe de ser un centro de intercambio vigente.';
            }
        }
        else
        {
            $msgError = 'El tiempo debe ser númerico y mayor que 0.';
        }
        return $success;
    }

    public function ajaxNewRoutePointAction()
    {
        $result = false; /// :(
        $this->view->setUseTemplate(false);
        if ($this->getRequest()->isPost() == true)
        {
            $post = $this->getRequest()->getPost();
            if (array_key_exists('routeId', $post) == true)
            {
                $em = $this->getEntityManager('DefaultDb');
                switch ($post['creationType'])
                {
                    //creacion del punto de ruta basado en un punto nuevo
                    case 1:
                        $pointsRepository = $em->getRepository('DefaultDb_Entities_Point');
                        if ($pointsRepository->existByCode($post['pointCode']) === true)
                        {
                            $this->view->result = 'Ya existe un punto de venta con esta clave.';
                            return;
                        }
                        //creacion de nuevo punto de venta/centro de intercambio
                        $point = new DefaultDb_Entities_Point;
                        $point->setCode($post['pointCode']);
                        $point->setName($post['pointName']);
                        $point->setType($post['pointType']);
                        $point->setStatus(DefaultDb_Entities_Point::STATUS_NORMAL);
                        $point->setAddress($post['pointAddress']);
                        $state = $em->getRepository('DefaultDb_Entities_State')->find($post['state']);
                        $point->setState($state);
                        if (($point->getCode() === null || $point->getCode() == '') || ($point->getName() === null || $point->getName() == '') || (empty($post['pointType'])) || ($point->getAddress() === null || $point->getAddress() == '')
                        )
                        {
                            $this->view->result = 'Todos los campos son requeridos.';
                            return;
                        }
                        /**
                         * Guardamos el branch en el usuario de tipo Cliente_Mas_Distribucion
                         */
                        $branch = new DefaultDb_Entities_BranchesUser;
                        $client = $em->getRepository('DefaultDb_Entities_User')->findOneByType(DefaultDb_Entities_User::USER_CLIENT_MAS_DISTRIBUCION);
                        if ($client)
                        {
                            $branch->setClient($client);
                            $branch->setDirection($post['pointAddress']);
                            $branch->setName($post['pointName']);
                            $branch->setPoint($point);
                            $em->persist($branch);
                        }
                        break;
                    case 4:
                    case 2: //creacion con respecto a la lista de puntos de venta
                    case 3: //creacion con respecto a la lista de centros de intercambio
                        /// Para cualquiera de estos tres casos verificamos
                        /// que se haya seleccionado un punto.
                        $pointId = $post['pointId'];
                        if ($pointId == 0)
                        {
                            $this->view->result = 'Es necesario especificar el punto de venta
                                / centro de intercambio 
                                / centro de intercambio de otra ruta';
                            return;
                        }
                        $existPointInRoute = $em->getRepository('DefaultDb_Entities_RoutePoint')->existPointInRoute($post['routeId'], $pointId);
                        if ($existPointInRoute === true)
                        {
                            $this->view->result = 'Ya existe el punto de venta en la ruta.';
                            return;
                        }
                        $point = $em->getRepository('DefaultDb_Entities_Point')->findOneBy(array(
                            'id' => $post['pointId']));
                        break;
                }
                /// Para todos los casos checamos que se haya definido un tiempo
                /// en minutos con respecto al punto anterior.
                $routePointArrivalTime = $post['routePointArrivalTime'];
                if ($routePointArrivalTime == null)
                {
                    $this->view->result = 'Es necesario especificar el tiempo con respecto
                al punto anterior. Ejemplo: 10.';
                    return;
                }
                if (ctype_digit($routePointArrivalTime) === false)
                {
                    $this->view->result = 'El tiempo con respecto al punto anterior
                    debe ser numerico. Ejemplo: 10.';
                    return;
                }
                //obtencion de la ruta
                $route = $em->getRepository('DefaultDb_Entities_Route')->findOneBy(array(
                    'id' => $post['routeId']));
                //creacion del punto de ruta
                $routePoint = new DefaultDb_Entities_RoutePoint;
                $routePoint->setRoute($route);
                $order = $em->getRepository('DefaultDb_Entities_RoutePoint')->getLastOrderNumberByRoute($route);
                $order++;
                $routePoint->setOrder($order); //obtener el ultimo
                $routePoint->setPoint($point);
                $routePoint->setStatus(DefaultDb_Entities_RoutePoint::STATUS_NORMAL);
                $arrivalTime = new DateTime();
                $arrivalTime->setTime(0, $post['routePointArrivalTime'], 0);
                $routePoint->setArrivalTime($arrivalTime);
                $em->persist($routePoint);
                $em->flush();
                $result = true;
            }
        }
        $this->view->result = $result;
    }

    public function stepUpRoutePointAction()
    {
        $params = $this->getRequest()->getParams();
        if (is_array($params) == true && array_key_exists('id', $params) == true && array_key_exists('routePointId', $params) == true)
        {
            //obtener el punto de ruta de a subir
            $em = $this->getEntityManager('DefaultDb');
            $routePointToStepUp = $em->getRepository('DefaultDb_Entities_RoutePoint')->find($params['routePointId']);

            //obtener el punto de ruta a bajar
            $routePointToStepDown = $em->getRepository('DefaultDb_Entities_RoutePoint')->getStepUpRoutePoint($params['id'], $routePointToStepUp->getOrder());
            if ($routePointToStepDown instanceof DefaultDb_Entities_RoutePoint == true && $routePointToStepDown->getId() != $routePointToStepUp->getId())
            {
                //guardar el valor del orden del punto a bajar en una variable temporal
                $tmpOrder = $routePointToStepDown->getOrder();

                //establecer nuevos valores de orden
                $routePointToStepDown->setOrder($routePointToStepUp->getOrder());
                $routePointToStepUp->setOrder($tmpOrder);

                //actualizar db
                $em->persist($routePointToStepDown);
                $em->persist($routePointToStepUp);
                $em->flush();
            }
            $this->redirect('Admin/Routes/points/id/' . $params['id']);
        }
        else
            $this->redirect('Admin/Routes');
    }

    public function stepDownRoutePointAction()
    {
        $params = $this->getRequest()->getParams();
        if (is_array($params) == true && array_key_exists('id', $params) == true && array_key_exists('routePointId', $params) == true)
        {
            //obtener el punto de ruta de a subir
            $em = $this->getEntityManager('DefaultDb');
            $routePointToStepDown = $em->getRepository('DefaultDb_Entities_RoutePoint')->find($params['routePointId']);

            //obtener el punto de ruta a bajar
            $routePointToStepUp = $em->getRepository('DefaultDb_Entities_RoutePoint')->getStepDownRoutePoint($params['id'], $routePointToStepDown->getOrder());

            if ($routePointToStepUp instanceof DefaultDb_Entities_RoutePoint == true && $routePointToStepUp->getId() != $routePointToStepDown->getId())
            {
                //guardar el valor del orden del punto a subir en una variable temporal
                $tmpOrder = $routePointToStepUp->getOrder();

                //establecer nuevos valores de orden
                $routePointToStepUp->setOrder($routePointToStepDown->getOrder());
                $routePointToStepDown->setOrder($tmpOrder);

                //actualizar db
                $em->persist($routePointToStepDown);
                $em->persist($routePointToStepUp);
                $em->flush();
            }
            $this->redirect('Admin/Routes/points/id/' . $params['id']);
        }
        else
            $this->redirect('Admin/Routes');
    }

    public function deleteRoutePointAction()
    {
        $params = $this->getRequest()->getParams();
        if (is_array($params) == true && array_key_exists('id', $params) == true && array_key_exists('routePointId', $params) == true)
        {
            //obtener el punto de ruta de a subir
            $em = $this->getEntityManager('DefaultDb');
            $routePointToDelete = $em->getRepository('DefaultDb_Entities_RoutePoint')->find($params['routePointId']);

            $routePointToDelete->setStatus(0);
            // $em->remove($routePointToDelete);
            $em->persist($routePointToDelete);
            $em->flush();
            $this->redirect('Admin/Routes/points/id/' . $params['id']);
        }
        else
            $this->redirect('Admin/Routes');
    }

    public function editRoutePointAction()
    {
        $params = $this->getRequest()->getParams();
        if (is_array($params) == true && array_key_exists('id', $params) == true && array_key_exists('routePointId', $params) == true)
        {
            //obtener el punto de ruta de a subir
            $em = $this->getEntityManager('DefaultDb');
            $routePointToEdit = $em->getRepository('DefaultDb_Entities_RoutePoint')->find($params['routePointId']);
            $this->view->routePoint = $routePointToEdit;
            $states = $em->getRepository('DefaultDb_Entities_State')->findAll();
            $this->view->states = $states;
        }
        else
            $this->redirect('Admin/Routes');
    }

    public function saveRoutePointAction()
    {
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            if (array_key_exists('routePointId', $post) == true)
            {
                $em = $this->getEntityManager('DefaultDb');
                $rp = $em->getRepository('DefaultDb_Entities_RoutePoint')->find($post['routePointId']);
                /* @var $rp DefaultDb_Entities_RoutePoint */
                $rp->getPoint()->setCode(trim(strtoupper($post['code'])));
                $rp->getPoint()->setName(trim(strtoupper($post['name'])));
                $rp->getPoint()->setType($post['type']);
                $rp->getPoint()->setAddress(trim(strtoupper($post['address'])));
                $state = $em->getRepository('DefaultDb_Entities_State')->find($post['state']);
                $rp->getPoint()->setState($state);
                $arrivalTime = new DateTime;
                $arrivalTime->setTime(0, $post['arrivalTime'], 0);
                $rp->setArrivalTime($arrivalTime);
                $em->flush();
                $this->view->routePoint = $rp;
            }
        }
    }

    /**
     * Esta acción se encarga de asignar un controlador de operaciones a una ruta.
     */
    public function AssignOperationsControllerAction()
    {
        $request = $this->getRequest();
        $newLogRouteToController = null;
        /**
         * SI viene por POST entonces es una nueva asignación de un controlador
         * de operaciones.
         */
        if ($request->isPost() === true)
        {
            $params = $request->getPost();
            $sesionUserId = Model3_Auth::getCredentials('id');
            $newLogRouteToController = $this->AssignOperationsController($params, $sesionUserId);
        }
        $routeId = $request->getParam('id');
        if ($routeId === null)
        {
            $this->redirect('Admin/Routes/index');
            return;
        }
        $em = $this->getEntityManager('DefaultDb');
        $routeRepository = $em->getRepository('DefaultDb_Entities_Route');
        $userRepository = $em->getRepository('DefaultDb_Entities_User');
        $logRouteToControllerRepository = $em->getRepository('DefaultDb_Entities_LogRouteToController');
        $route = $routeRepository->find($routeId);
        if ($route === null)
        {
            $this->redirect('Admin/Routes/index');
            return;
        }
        $operationController = $logRouteToControllerRepository->getOperationControllerByRoute($routeId); #Controlador de esta ruta
        $operationControllers = $userRepository->getActiveOperationControllers(); #todos los controladores activos
        $this->view->whereAmI = array(
            'Rutas' => $this->view->url(array('module' => 'Admin', 'controller' => 'Routes',
                'action' => 'index')));
        $this->view->operationController = $operationController;
        $this->view->newLogRouteToController = $newLogRouteToController;
        $this->view->setTemplate('responsive-3.0');
        $this->view->route = $route;
        $this->view->operationControllers = $operationControllers;
        $this->view->title = 'Asignar controlador de operaciones';
        $this->view->description = 'Asignar controlador de operaciones que se encargará de administrar y supervisar la ruta';
    }

    /**
     * Asignamos la ruta a un controlador.
     * @param array $params Arreglo con los parametros recibidos por post
     * @param integer $sesionUserId Id del usuario con la sesion activa
     * @return DefaultDb_Entities_LogRouteToController
     */
    private function AssignOperationsController($params, $sesionUserId)
    {
        $newLog = null;
        if (isset($params['routeId']) === true && isset($params['controllerId']))
        {
            $em = $this->getEntityManager('DefaultDb');
            $logRouteToControllerRepository = $em->getRepository('DefaultDb_Entities_LogRouteToController');
            $usersRepository = $em->getRepository('DefaultDb_Entities_User');
            $routeRepository = $em->getRepository('DefaultDb_Entities_Route');
            $routeId = $params['routeId'];
            $controllerId = $params['controllerId'];
            $route = $routeRepository->find($routeId);
            $sesionUser = $usersRepository->find($sesionUserId);
            $controller = $usersRepository->find($controllerId);
            if ($route !== null && $controller !== null && $sesionUser !== null)
            {
                $route->setController($controller);
                $em->persist($route);
                $em->flush();
                $newLog = $logRouteToControllerRepository->add($route, $controller, $sesionUser);
            }
        }
        return $newLog;
    }

}